import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    port: 3004,
    open: true,
    proxy: {
      '/api': {
        target: 'https://49.232.231.56',  // 直接使用HTTPS
        changeOrigin: true,
        secure: false, // 忽略SSL证书错误
        logLevel: 'debug',
        rewrite: (path) => {
          // 将 /api/v1 重写为 /v1
          const newPath = path.replace(/^\/api/, '')
          console.log(`代理重写: ${path} -> ${newPath}`)
          return newPath
        },
        configure: (proxy, options) => {
          proxy.on('error', (err, req, res) => {
            console.log('代理错误:', err.message)
          })
          proxy.on('proxyReq', (proxyReq, req, res) => {
            console.log('发送代理请求:', req.method, req.url)
            // 设置必要的请求头
            proxyReq.setHeader('Origin', 'https://49.232.231.56')
            // 确保Content-Type正确传递
            if (req.headers['content-type']) {
              proxyReq.setHeader('Content-Type', req.headers['content-type'])
            }
          })
          proxy.on('proxyRes', (proxyRes, req, res) => {
            console.log('收到代理响应:', proxyRes.statusCode, req.url)
            // 添加CORS头
            res.setHeader('Access-Control-Allow-Origin', '*')
            res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
            res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
            res.setHeader('Access-Control-Allow-Credentials', 'true')
          })
        }
      }
    }
  }
})